package com.abe.libfitness.utils;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.LocaleList;
import android.util.DisplayMetrics;

import com.abe.libcore.utils.CommonUtils;

import java.util.Locale;

public class AppLanguageUtils {
    public static Context attachBaseContext(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return updateResources(context);
        } else {
            language(context);
            return context;
        }
    }

    //更改应用语言
    @SuppressLint("ObsoleteSdkInt")
    public static void language(Context context) {
        String language = SpFitnessHelper.language();
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        Configuration configuration = resources.getConfiguration();
        CommonUtils.INSTANCE.log("changeAppLanguage:" + language);
        Locale locale;
        if (language.equals(ConstantFitness.LANGUAGE_EN)) {// 英文
            locale = Locale.ENGLISH;
        } else {
            locale = Locale.SIMPLIFIED_CHINESE;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            configuration.setLocale(locale);
            configuration.setLocales(new LocaleList(locale));
            context.createConfigurationContext(configuration);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration.setLocale(locale);
        } else {
            configuration.locale = locale;
        }
        resources.updateConfiguration(configuration, metrics);
    }

    @SuppressLint("ObsoleteSdkInt")
    @TargetApi(Build.VERSION_CODES.N)
    private static Context updateResources(Context context) {
        Resources resources = context.getResources();
        Configuration config = resources.getConfiguration();
        String language = SpFitnessHelper.language();
        CommonUtils.INSTANCE.log("updateResources:" + language);
        Locale locale;
        if (language.equals(ConstantFitness.LANGUAGE_EN)) {// 英文
            locale = Locale.ENGLISH;
        } else {
            locale = Locale.SIMPLIFIED_CHINESE;
        }
        config.setLocale(locale);
        config.setLocales(new LocaleList(locale));
        return context.createConfigurationContext(config);
    }
}